package com.feibi.ht300_printer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.flutter.plugin.common.MethodChannel;
import tspl.HPRTPrinterHelper;

public class HT300Util {
    private HPRTPrinterHelper HPRTPrinter = new HPRTPrinterHelper();

    public void connect(Context context, String strIP, String strPort, MethodChannel.Result result) {
        try {
            if (HPRTPrinter != null) {
                HPRTPrinter.PortClose();
            }
            if (strIP.length() == 0) {
                result.error("400", "ip地址為空", null);
                return;
            }
            if (HPRTPrinterHelper.PortOpen("WiFi," + strIP + "," + strPort) != 0) {
                result.error("400", "連接失敗", null);
            } else {
                HPRTPrinterHelper.PortClose();
                result.success(true);
            }
            HPRTPrinter = null;
        } catch (Exception e) {
            result.error("400", "連接失敗:" + e.getMessage(), null);
            Log.d("HPRTSDKSample", (new StringBuilder("Activity_Wifi --> onClickConnect ")).append(e.getMessage()).toString());
        }
    }


    public void disconnect(MethodChannel.Result result) {
        try {
            HPRTPrinterHelper.PortClose();
            result.success(true);
            return;
        } catch (Exception e) {
            result.error("400", "ip地址為空", null);
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }



    public void printText(String text, MethodChannel.Result result) {
        try {
//            Print.LanguageEncode = "gb2312";
//            Print.LanguageEncode = "big5";
//            Print.SetCharacterSet((byte)0);
//            Print.PrintText(text);
//            Print.CutPaper(1,10);
        } catch (Exception e) {
            e.printStackTrace();
            result.error("400", e.getMessage(), "");
        }
    }

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public void printImage(String filePath, int size, MethodChannel.Result result) {
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Bitmap bmp = BitmapFactory.decodeFile(filePath);
//                    if (size != 0)
//                        bmp = Utility.Tobitmap(bmp, size, Utility.getHeight(size, bmp.getWidth(), bmp.getHeight()));
//                    Print.PrintBitmap(bmp, 1, 0);
//                    bmp.recycle();
//                    Print.CutPaper(1,10);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    result.error("400", e.getMessage(), "");
//                }
//            }
//        });
    }

}

